/*
* 工序内容内容管理模块
*/
const express = require('express');
const router = express.Router();
// 引入数据库
const db = require("../../../config/db");
// 引入时间包
const moment = require("moment");
// 引入方法库
const { toCamelCase, toUnderlineCase, verifyToken} = require("../../../config/utils");
// 引入日志
const log = require("../../log");

// 查询所有生产工序内容
router.get("/list", (req, res) => {
    console.log("===========查询所有生产工序内容接口============");
    // 获取参数
    let {pageNum, pageSize, orderNum, processName, enableFlag} = req.query;
    // 拼接sql语句
    let sql = "select * from pro_process_content";
    let sql_where = ` where 1=1`;
    if(orderNum){
        sql_where += ` and order_num like '%${orderNum}%'`;
    }
    if(processName){
        sql_where += ` and process_name like '%${processName}%'`;
    }
    if(enableFlag){
        sql_where += ` and enable_flag = '${enableFlag}'`;
    }
    if(orderNum || processName  || enableFlag){
        sql += sql_where;
    }
    
    // 分页
    sql += ` limit ${(pageNum-1)*pageSize}, ${pageSize}`;
    // 查询数据库
    db.query("查询生产工序内容列表", sql, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询生产工序内容列表失败", data: err});
            return;
        }
        // 查询总数
        db.query("查询生产工序内容总数", `select count(*) as count from pro_process_content ${sql_where}`, (err, count)=>{
            if(err){
                res.send({code: 500, msg: "查询生产工序内容总数失败", data: err});
                return;
            }
            if(result.length > 0){
                 // 变量Json数组key转成下划线第一个大写
                 result = result.map(item => {
                    return toCamelCase(item)
                })
                res.send({code: 200, msg: "查询生产工序内容列表成功", rows: result, total: count[0].count});
            }else{
                res.send({code: 200, msg: "查询生产工序内容列表成功", data: [], total: 0});
            }
        })
    })
})

// 添加生产工序内容
router.post("/", async (req, res) => {
    console.log("===========添加生产工序内容接口============");
    // 获取参数
    let { orderNum, docUrl, device, material, contentText, remark, processId } = req.body;
     // 获取创建人
     let {username} = verifyToken(req.headers.authorization);
     // 获取创建时间
     let createTime = moment().format("YYYY-MM-DD HH:mm:ss");
     // 判断生产工序内容编码
     db.query("查询生产工序内容编码是否重复", `select * from pro_process_content where order_num='${orderNum}'`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询生产工序内容编码是否重复失败", data: err});
            return;
        }
        if(result.length > 0){
            res.send({code: 500, msg: "生产工序编码已存在", data: []});
            return;
        }
        // 插入数据库
        let sql = `insert into pro_process_content (order_num, doc_url, device, material, content_text, remark, create_by, create_time, process_id) 
        values('${orderNum}', ${docUrl ? "'"+docUrl+"'" : null}, ${device ? "'"+device+"'" : null}, ${material ? "'"+material+"'" : null}, 
        ${contentText ? "'"+contentText+"'" : null}, ${remark ? "'"+remark+"'" : null}, '${username}', '${createTime}', '${processId}')`;
        db.query("添加生产工序内容", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "添加生产工序内容失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "添加生产工序内容成功", data: []});
            }else{
                res.send({code: 500, msg: "添加生产工序内容失败", data: []});
            }
        })
     })
})

// 查询单个生产工序内容
router.get(/^\/(\d+)$/, (req, res) => {
    console.log("===========查询单个生产工序内容接口，正则匹配============");
    // 获取参数
    let url_arr = req.url.split("/");
    const id = url_arr[url_arr.length - 1];
   
    db.query("查询单个生产工序内容", `select * from pro_process_content where content_id = ${id}`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询单个生产工序内容失败", data: err});
            return;
        }
        if(result.length > 0){
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
                return toCamelCase(item)
            })
            res.send({code: 200, msg: "查询单个生产工序内容成功", data: result[0]});
        }else{
            res.send({code: 500, msg: "查询单个生产工序内容失败"});
        }
    })
})

// 修改生产工序内容
router.put("/", (req, res)=>{
    console.log("===========修改生产工序内容接口============");
    // 获取参数
    let {contentId, orderNum, docUrl, device, material, contentText, remark, processId } = req.body;
    // 获取修改人
    let {username} = verifyToken(req.headers.authorization);
    // 获取修改时间
    let updateTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 查询顺序编号是否重复
    db.query("查询顺序编号是否重复", `select * from pro_process_content where content_id != ${contentId} and order_num = '${orderNum}'`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询顺序编号是否重复失败", data: err});
            return;
        }
        if(result.length > 0){
            res.send({code: 500, msg: "顺序编号已存在", data: []});
            return;
        }
        // 修改生产工序内容sql
        let sql = `update pro_process_content set order_num='${orderNum}', doc_url = ${docUrl ? "'"+docUrl+"'" : null},
        device=${device ? "'"+device+"'" : null}, material = ${material ? "'"+material+"'" : null}, remark=${remark ? "'"+remark+"'" : null}, 
        update_by='${username}', content_text=${contentText ? "'"+contentText+"'" : null}, update_time='${updateTime}' where content_id = ${contentId}`;
        db.query("修改生产工序内容", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "修改生产工序内容失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "修改生产工序内容成功", data: []});
            }else{
                res.send({code: 500, msg: "修改生产工序内容失败", data: []});
            }
        })
    })
})

// 删除生产工序内容
router.delete("/:id", (req, res) => {
    console.log("===========删除生产工序内容接口============");
    // 获取参数
    let {id} = req.params;
     // 拼接sql,删除多条数据
     let sql = `delete from pro_process_content where content_id in(${id})`;
    // 查询数据库
    db.query("删除生产工序内容", sql, (err, result) => {
        if (err) {
            res.send({code: 500, msg: "删除生产工序内容失败", data: err});
            return
        }
        if(result.affectedRows > 0){
            res.send({code: 200, msg: "删除生产工序内容成功"})
        }else{
            res.send({code: 500, msg: "删除生产工序内容失败"})
        }
    })
})


module.exports = router;